//tcp_sock.c by cme
#include "tcp_sock.h"
#include <sys/types.h>

#ifdef _WIN32
#include <Winsock.h>
#include <Winbase.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/socket.h>
#include <netinet/in.h>
#endif
void init_network()
{
#ifdef _WIN32
	WSADATA w;
    	if(WSAStartup(0x0101, &w) != 0)
	{
		exit(0);
    	}
#endif
}

int tcp_connect(const char* szIP, unsigned short port)
{
	struct sockaddr_in tem_addr;
	int nSockfd = 0;
	if(!szIP) 
	{
		return -1;
	}
	else
	{
		tem_addr.sin_family = AF_INET;	
		tem_addr.sin_addr.s_addr = inet_addr(szIP);
		tem_addr.sin_port = htons(port);
	}
	
	if((nSockfd = socket(AF_INET, SOCK_STREAM, 0 )) < 0)
	{
		return -1;
	} 
	
	if(connect(nSockfd, (struct sockaddr*)&tem_addr, sizeof(tem_addr)) == 0)
	{
		return nSockfd;
	}
	return  -1;
}

int tcp_listen_port(unsigned short uPort)
{
    	struct sockaddr_in server_addr;
	int nSockfd = 0;
	if((nSockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		return -1;
	}
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(uPort);
	server_addr.sin_addr.s_addr = htons(INADDR_ANY);
	if(bind(nSockfd, (struct sockaddr*)(&server_addr), sizeof(struct sockaddr)) < 0)
	{
		perror("bind");
#ifdef _WIN32
		closesocket(nSockfd);
#else
		close(nSockfd);
#endif
		return -1;
	}
	
	if(listen(nSockfd, 5) < 0)
	{
		perror("listen");
#ifdef _WIN32
		closesocket(nSockfd);
#else
		close(nSockfd);
#endif
		return -1;
	}
	return nSockfd;
}
int tcp_close(int nSockfd)
{
	#ifdef _WIN32
		closesocket(nSockfd);
#else
		close(nSockfd);
#endif
		return 1;
}
